<template>
  <el-container style="padding: 20px;">
    <el-card class="box-card" style="max-width: 600px; margin: 0 auto;">
      <div slot="header" class="card-header">
        添加用户
      </div>
      <el-form :model="user" ref="userForm" label-width="80px" @submit.native.prevent="submitForm">
        <el-form-item label="账号" prop="username" :rules="[{ required: true, message: '请输入账号', trigger: 'blur' }]">
          <el-input v-model="user.username" placeholder="请输入账号" autocomplete="off" />
        </el-form-item>

        <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input v-model="user.password" placeholder="请输入密码" autocomplete="off" show-password />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname" :rules="[{ required: true, message: '请输入昵称', trigger: 'blur' }]">
          <el-input v-model="user.nickname" placeholder="请输入昵称" autocomplete="off" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email" :rules="[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,
            message: '邮箱格式不正确',
            trigger: ['blur', 'change']
          }
        ]">
          <el-input v-model="user.email" placeholder="请输入邮箱" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">立即提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
        <div style="position: absolute; right: 20px; bottom: 20px;">
          <el-button type="info" @click="goBack">返回用户列表</el-button>
        </div>
      </el-form>

    </el-card>
  </el-container>
</template>

<script>
import { add } from '@/api/auth'

export default {
  name: 'AddUser',
  data() {
    return {
      user: {
        username: '',
        password: '',
        nickname: '',
        email: ''
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.userForm.validate(valid => {
        if (!valid) return

        add(this.user)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('用户添加成功')
                this.$router.push('/user')
              } else {
                this.$message.error(res.msg || '添加用户失败')
              }
            })
            .catch(() => {
              this.$message.error('添加用户失败')
            })
      })
    },
    resetForm() {
      this.$refs.userForm.resetFields()
    },
    goBack() {
      this.$router.push('/user');
    }
  }
}
</script>

<style scoped>
.box-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.card-header {
  font-size: 18px;
  font-weight: 600;
}
</style>
